// index.ts
// 获取应用实例
const app = getApp<IAppOption>()
let inputVal = ""
let msgList: any = [];
let windowWidth = wx.getWindowInfo().windowWidth;
let windowHeight = wx.getWindowInfo().windowHeight;
let keyHeight = 0;

let socketOpen = false;
let socketMsgQueue = [];
let lineCount = Math.floor(windowWidth / 16) - 6;
let curAnsCount = 0;

function initData(that: any) {
  inputVal = "";
  msgList = [{
    speaker: "server",
    contentType: "text",
    content: "你好，我是人工智能助手"
  }]
  that.setData({
    msgList,
    inputVal
  })
}

function sendSocketMessage(msg: any) {
  if (socketOpen) {
    wx.sendSocketMessage({
      data: msg
    })
  } else {
    socketMsgQueue.push(msg);
  }
}

Page({
  data: {
    scrollHeight: '100vh',
    inputBottom: 0
  },
  focus: function (e: any) {
    let res = wx.getWindowInfo();
    let navBarHeight = res.statusBarHeight + 44;
    keyHeight = e.detail.height - navBarHeight;
    if (keyHeight < 0) {
      keyHeight = 0
    }
    this.setData({
      scrollHeight: (windowHeight - keyHeight) + 'px'
    });
    this.setData({
      toView: 'msg-' + (msgList.length - 1),
      inputBottom: (keyHeight) + 'px'
    })
  },
  blur: function (e) {
    this.setData({
      scrollHeight: '100vh',
      inputBottom: 0
    })
    this.setData({
      toView: 'msg-' + (msgList.length - 1)
    })
  },
  sendClick: function (e) {
    sendSocketMessage(e.detail.value)
    msgList.push({
      speaker: 'customer',
      contentType: 'text',
      content: e.detail.value
    })
    msgList.push({
      speaker: 'server',
      contentType: 'text', 
      content: ''
    })
    
    inputVal = '';
    this.setData({
      msgList,
      inputVal
    });
  },
  toBackClick: function () {
    wx.navigateBack({})
  },
  onLoad: function (options) {
    initData(this);
    console.log(options)

  },
  onShow: function () {
    wx.setStorageSync("userId", 1);
    wx.connectSocket({
      url: "ws://127.0.0.1:8080//websocket/" + wx.getStorageSync("userId")
    })
    wx.onSocketOpen((res) => {
      socketOpen = true;
      console.log(res)
      console.log("打开socket");
      wx.showToast({
        icon: "none",
        title: "会话建立成功！",
        duration: 500
      })
      socketMsgQueue = [];
      wx.onSocketMessage((result) => {
        console.log(result.data);
        curAnsCount++;
        if (curAnsCount % lineCount == 0) {
          wx.createSelectorQuery().select("#chatPage").boundingClientRect(function (rect) {
            wx.pageScrollTo({
              scrollTop: rect.bottom
            })
          }).exec();
        }
        msgList[msgList.length - 1].content = msgList[msgList.length - 1].content + result.data;
        this.setData({
          msgList
        })
      })
    })
  },
  onHide: function () {
    wx.closeSocket();
    wx.onSocketClose((result) => {
      console.log("socket关闭成功!");
      console.log(result)
      wx.showToast({
        icon: "none",
        title: "会话关闭成功",
        duration: 500
      })
    })
  },
  methods: {
  },
})
